﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LispInterpretor.HelperClasses;

namespace LispInterpretor.Parsers
{
    internal class CondParser : IParser
    {
        public bool Is(string text, Environment environment)
        {
            return text.StartsWith("(cond ", StringComparison.InvariantCultureIgnoreCase) && text.EndsWith(")");
        }

        public object Evaluate(string text, Environment environment)
        {
            IList<string> arguments = ParserHelper.ParseArguments(text);

            Check.IsTrue(arguments.Count >= 2, "Cond requires at least one sub-expression");

            for (int i = 1; i < arguments.Count; i++)
            {
                string argument = arguments[i];

                IList<string> subExpressionPieces = ParserHelper.ParseArguments(argument);

                Check.IsTrue(subExpressionPieces.Count == 2, "Cond has encountered a sub-expression with too many parts.");

                object predicate = Evaluator.Eval(subExpressionPieces[0], environment);

                Check.IsTrue(predicate is bool, "Cond has encountered a sub-expression whose first part does not evaluate to bool.");

                if ((bool)predicate)
                {
                    return Evaluator.Eval(subExpressionPieces[1], environment);
                }
            }

            throw new InvalidProgramException("Cond didn't find any sub-expression whose first part evaluated to true.");
        }
    }
}
